/**
 * 数据分页插件 - 2.1.1
 * 作者：胡永伟
 * 时间：2015-10-23
 * 实现：本插件通过ajaxSubmit异步获取后台数据,返回数据为json类型,接口具体返回参数：
 */

function DPTLister(options) {
	this.options = $.extend({
		ID : 'list_table',
		columns : null,
		adapter : null,
		pagelen : null,
		sortall : null,
		defined : null,
		o_color : '#f6f8fa',
		e_color : '#ffffff',
		wrapped : null,
		fixedly : null,
		landing : null,
		sortway : null,
		fuzzies : null
	}, options);
	this.init = function() {
		var self = this,
			opts = self.options,
			node = "",
			href = "href='javascript:;'",
			$root = $("#" + opts.ID);
		$root.html("");
		self.options.adapter = self.options.adapter || self.adapter;
		self.options.pagelen = self.options.pagelen || self.pagelen || 20;
		self.options.landing = self.options.landing || self.landing || 99;
		self.options.sortall = self.options.sortall == null ? self.sortall : self.options.sortall;
		self.options.fixedly = self.options.fixedly == null ? self.fixedly : self.options.fixedly;
		if (opts.defined) {
			node += "<div id='dptl_data_list_box' style='width:100%;'></div>";
		} else {
			var cols = opts.columns, width = 0;
			for (var i = 0; cols && i < cols.length; i++) {
				if ( cols[i].width) {
					cols[i].width = (cols[i].width + "").match(/\d+(.\d+)?/)[0];
				}
				if (!cols[i].width) {
					cols[i].width = 100 / cols.length;
				}
				cols[i].width = parseFloat(cols[i].width).toFixed(1);
				width += (cols[i].width = parseFloat(cols[i].width));
			}
			var symbol, arg = 0, sup = 0, attrs = [], ths = '', tds = '';
			symbol = (width > 100) ? (-1) : 1;
			arg = parseFloat(Math.abs(width - 100) / cols.length).toFixed(1);
			sup = Math.abs(width - 100) - arg * cols.length + 1;
			//console.log("width:" + width + ",arg:" + arg + ",sup:" + sup + ",symbol:" + symbol);
			for (var i = 0; cols && i < cols.length; i++) {
				cols[i].width += Math.round(arg * symbol + (i == cols.length - 1 ? sup : 0) * 10) / 10;
				cols[i].width += '%';
				if (cols[i].sort || opts.sortall) {
					ths += ("<th class='dptl-mouse-hand dptl-fr-normal' width='" + 
									cols[i].width + "' key='" + (cols[i].search||cols[i].field) + "'>" + cols[i].name +
							"</th>");
				} else { 
					ths += ("<th width='" + cols[i].width + "' key='" +
					(cols[i].search||cols[i].field) + "'>" + cols[i].name + "</th>");
				}
				var align;
				if (cols[i].align == "left") { 
					align = "td-align-left"; 
				} else if (cols[i].align == "right") { 
					align = "td-align-right"; 
				} else { 
					align = "td-align-center"; 
				}
				var cv = cols[i].value ? cols[i].value : "#" + cols[i].field + "#";
				tds += ("<td width='" + cols[i].width + "' class='" + align + "'><div>" + cv + "</div></td>");
				var vs = cv.match(/#[^#]+#/g);
				for (var j = 0; vs && j < vs.length; j++) {
					var attr = vs[j].substr(1, vs[j].length - 2);
					if (!(attr in attrs)) {
						attrs.push(attr); 
					} 
				}
			}
			opts.attrs = attrs;
			node += "<div id='dptl_data_title'>" +
						"<table class='dptl-title' border='0' cellspacing='0' cellpadding='0'>" +
							"<tr>" + ths + "</tr>" +
						"</table>" +
					"</div>" +
					"<div id='dptl_data_root'>" +
						"<table class='dptl-table' border='0' cellspacing='0' cellpadding='0'>" +
							"<tbody id='dptl_data_list_table'></tbody>" +
						"</table>" +
					"</div>" +
					"<table style='display: none'>" +
						"<tbody id='dptl_data_list_model'><tr>" + tds + "</tr></tbody>" +
					"</table>";
		}
		node += "<div id='dptl_page_root' class='dptl-page'>" +
					"<input type='hidden' id='dptl_page_num' name='pagenum' value='1'/>" +
					"<input type='hidden' id='dptl_page_len' name='pagelen' value='" + opts.pagelen + "'/>" +
					"<input type='hidden' id='dptl_page_total' value='0'/>" +
					"<input type='hidden' id='dptl_sort_key' name='sortway' value=''/>" +
					"<input type='hidden' name='fuzzies' value='" + opts.fuzzies + "'/>" +
					"<span id='dptl_record_info' class='record'></span>" +
					"<div id='dptl_page_root_operate' style='float: right;'>" +
						"<a " + href + " id='dptl_first_page'>\u9996\u3000\u9875</a>" +
						"<a " + href + " id='dptl_previou_page'>\u4e0a\u4e00\u9875</a>" +
						"<span id='dptl_page_info' class='pages'></span>" +
						"<a " + href + " id='dptl_next_page'>\u4e0b\u4e00\u9875</a>" +
						"<a " + href + " id='dptl_last_page'>\u5c3e\u3000\u9875</a>" +
						"<input type='text' id='dptl_page_input' />" +
						"<a " + href + " id='dptl_input_page'>\u8df3\u3000\u8f6c</a>" +
					"</div>" +
				"</div>" +
				"<div id='dptl_no_data_tip' class='dptl-tip'>" +
					"<span>\u672a\u641c\u7d22\u5230\u76f8\u5173\u6570\u636e...</span>" +
				"</div>";
		$root.append($(node)).find("#dptl_page_root a").click(function() { 
				dptlso.goTargetPage(self, this); 
		});
		if (!opts.defined) {
			$root.find(".dptl-title tr th.dptl-mouse-hand").click(function() {
				var tp;
				if ($(this).hasClass("dptl-fr-normal")) { 
					tp = 1;
				} else if ($(this).hasClass("dptl-fr-up")) { 
					tp = 2;
				} else if ($(this).hasClass("dptl-fr-down")) { 
					tp = 3; 
				}
				$root.find(".dptl-title tr th.dptl-mouse-hand")
						.removeClass("dptl-fr-up dptl-fr-down")
						.addClass("dptl-fr-normal");
				switch (tp) {
					case 1 : 
						$(this).removeClass("dptl-fr-normal").addClass("dptl-fr-up"); 
						$root.find("#dptl_sort_key").val($(this).attr("key") + " asc");
						break;
					case 2 : 
						$(this).removeClass("dptl-fr-up").addClass("dptl-fr-down");
						$root.find("#dptl_sort_key").val($(this).attr("key") + " desc"); 
						break;
					case 3 : 
						$(this).removeClass("dptl-fr-down").addClass("dptl-fr-up");
						$root.find("#dptl_sort_key").val($(this).attr("key") + " asc");
						break; 
				}
				self.list(true); 
			}); 
		}
		$root.find("#dptl_sort_key").val(opts.sortway);
		if ($("#dptl_data_load_div").length == 0) {
			$("body").append($("<div id='dptl_data_load_div' class='dptl-load'></div>")); 
		}
		return self;
	};
	this.list = function(unrefresh) {
		var self = this,
			$root = $("#" + self.options.ID),
			page = 1,
			key = location.href + '#' + self.options.ID,
			store = new LeopardStorage('dptlister.page');
		if (unrefresh) {
			var _page = store.get(key);
			page = (_page && _page[0].value) || page;
		}
		store.set(key, new String(page));
		$root.find("#dptl_page_num").val(page);
		$("#dptl_data_load_div").show();
		$root.parents("form").ajaxSubmit({
			beforeSubmit : function(form, info, opts) {
				var $root_wrap_height= $root.parents(".st-content-inner").height();
				$root.parents(".page-section").height($root_wrap_height);
				var data = {};
				for (var i = 0; i < form.length; i++) {
					data[form[i].name] = form[i].value;
				}
				var _r = self.options.adapter.tx(data);
				if (_r) {
					data = _r;
				}
				$.ajax({
					url : opts.url,
					type : 'post',
					data : data,
					dataType : 'json',
					timeout : 50000,
					async : true,
					success : function(response) {
						var _r = self.options.adapter.rx(response);
						if (_r) {
							response = _r;
						}
						$("#dptl_data_load_div").hide();
						dptlso.setPageInfo(self, response);
						if (self.options.defined) {
							var options = {
								'temlstr' : self.options.temlstr,
								'refresh' : true,
								'jsonarr' : response.data,
							};
							if ($.isFunction(self.options.process)) {
								options.process = self.options.process;
							}
							$("#dptl_data_list_box").pushin(options);
						} else {
							var objs = response.data, result = "";
							var $data_root = $root.find("#dptl_data_root");
							var $table = $root.find("#dptl_data_list_table");
							if (objs != null && objs.length > 0) {
								var template = $root.find("#dptl_data_list_model").html(),
									attrs = self.options.attrs;
								for (var i = 0; i < objs.length; i++) {
									var cell = template;
									if ($.isFunction(self.options.process)) {
										var _result = self.options.process(cell, objs[i]);
										if (_result) {
											cell = _result;
										}
									}
									for (var p in attrs) {
										//var val = objs[i][attrs[p]] ? objs[i][attrs[p]] : "";
										var val = (objs[i][attrs[p]] == null) ? "" : objs[i][attrs[p]];
										cell = cell.split("#" + attrs[p] + "#").join(val);
									}
									result += cell;
								}
								$table.html(result);
								$data_root.show();
							}else{
								$data_root.hide();
							}

							if (self.options.fixedly) {
								var height = document.documentElement.clientHeight;
								height -= 110;
								var pageSection=$root.parents(".page-section");
								pageSection.height(height);//内容区
								var searchDivHeight=pageSection.find(".panel-body").height()+20;//筛选区
								var pageRootHeight=$("#dptl_page_root ").height()+30;//页码区
								var thTitle=$("#dptl_data_title").height();
								var dataRootHeight=height-searchDivHeight-pageRootHeight-thTitle;//表格区
								var section_height=pageSection.height()!=null?dataRootHeight:360;//判端是否为弹出框
								//console.log(pageSection.height())
								var tableHeight;
								setTimeout(function(){
									var dataTableHeight=$table.height()+6;//表格内容高度
									//console.log(section_height>=dataTableHeight?dataTableHeight:section_height)
									//console.log( "se:"+section_height+""+"da:"+dataTableHeight);
									if(section_height>0){
										tableHeight=section_height>dataTableHeight?dataTableHeight:section_height
									}else{
										tableHeight=dataTableHeight
									}
									$data_root.height(tableHeight).niceScroll({
										'cursorcolor' : 'rgb(22, 174, 159)',
										'cursoropacitymax' : 1,
										'touchbehavior' : false,
										'cursorwidth' : '5px',
										'cursorborder': '0',
										'cursorborderradius' : '5px'
									});
									var tableScroll=$data_root.getNiceScroll();
									$data_root.hover(function(){
										tableScroll.show();
									},function(){
										tableScroll.hide();
									})
								},100);
							}
							$table.find("tr:even").css("background-color", self.options.e_color);
							$table.find("tr:odd").css("background-color", self.options.o_color);
							if (!self.options.wrapped) {
								$.each($table.find("div"), function() {
									//$(this).css('width', $(this).parent().css('width'));
									$(this).css('white-space', 'wrap');
									$(this).attr('title', $(this).text());
								});
							}
						}
						if ($.isFunction(self.options.finally)) {
							self.options.finally(response);
						}
					}
				});
				return false;
			}
		});
		return self;
	};
}

var dptlso = {
	setPageInfo : function(dptl, response) {
		var $root = $("#" + dptl.options.ID), curRecord,
			$data_root = $root.find("#dptl_data_root"),
			$data_title = $root.find("#dptl_data_title"),
			$page_root = $root.find("#dptl_page_root"),
			$page_num = $root.find("#dptl_page_num"),
			$page_len = $root.find("#dptl_page_len"),
			$page_tip = $root.find("#dptl_no_data_tip"),
			$fp = $root.find("#dptl_first_page,#dptl_previou_page"),
			$nl = $root.find("#dptl_next_page,#dptl_last_page"),
			$ip = $root.find("#dptl_input_page,#dptl_page_input"),
			pagenum = parseInt($page_num.val()),
			pagelen = parseInt($page_len.val()),
			total_count = response.total_count;
		if (!response.data || !total_count) { 
			$page_root.hide();

			if(response.data){
				if(response.data.length==0){
					$page_tip.find("span").html("未找到相关数据！");
				}
			}else{
				if (response.errmsg) {
					if(response.response.msg){
						$page_tip.find("span").html(response.response.msg);
					}else{
						$page_tip.find("span").html(response.errmsg);
					}

				}
			}
			$page_tip.show();
			if (!dptl.options.defined) {
				$data_root.hide();
				$data_title.css('overflow-y', 'hidden');
			}
			return; 
		}
		var total_pages = (total_count + pagelen - 1) / pagelen,
			cur_records = (total_count - pagenum * pagelen) < 0;
		total_pages = parseInt(total_pages);
		cur_records = cur_records ? total_count % pagelen : pagelen;
		$root.find("#dptl_page_num").val(pagenum);
		$root.find("#dptl_page_total").val(total_pages);
		$page_tip.hide();
		$page_root.show();
		$root.find("#dptl_record_info").html(
				"\u641c\u7d22\u7ed3\u679c\uff1a\u5171\u641c\u7d22\u5230" +
				"&nbsp;" + total_count + "&nbsp;" +
				"\u6761\u8bb0\u5f55\uff0c\u5f53\u524d\u663e\u793a" +
				"&nbsp;" + cur_records + "&nbsp;" + "\u6761\u8bb0\u5f55");
		$root.find("#dptl_page_info").html(
				pagenum + "&nbsp;/&nbsp;" + total_pages + "&nbsp;\u9875");
		if (pagenum <= 1) { 
			$fp.attr('disabled', true); 
		} else { 
			$fp.attr('disabled', false); 
		}
		if (pagenum >= total_pages) { 
			$nl.attr('disabled', true);
		} else { 
			$nl.attr('disabled', false); 
		}
		if (total_pages <= 1) { 
			$ip.attr('disabled', true);
		} else { 
			$ip.attr('disabled', false); 
		}
		if (response.psingle) { 
			$root.find("#dptl_page_root_operate").hide(); 
			return; 
		}
	},
	goTargetPage : function(dptl, btn) {
		var $root = $("#" + dptl.options.ID), key = btn.id;
			pagenum = parseInt($root.find('#dptl_page_num').val());
			total_pages = parseInt($root.find('#dptl_page_total').val());
		if (key == 'dptl_first_page') { 
			pagenum = 1;
		} else if (key == 'dptl_previou_page') { 
			pagenum = pagenum > 1 ? (--pagenum) : pagenum;
		} else if (key == 'dptl_next_page') { 
			pagenum = pagenum < total_pages ? (++pagenum) : pagenum;
		} else if (key == 'dptl_last_page') { 
			pagenum = total_pages;
		} else if (key == 'dptl_input_page') { 
			var $page_ipt = $root.find('#dptl_page_input'),
				pagenum_ipt = $page_ipt.val(), i_pagenum_ipt = parseInt(pagenum_ipt);
			if (pagenum_ipt == i_pagenum_ipt) {
				if (i_pagenum_ipt < 1 || i_pagenum_ipt > total_pages) {
					alert('\u9875\u7801\u4e0d\u5728\u8303\u56f4\u5185'); 
					$page_ipt.val("");
					return;
				} else { 
					pagenum = i_pagenum_ipt; 
				}
			} else { 
				alert('\u8f93\u5165\u9875\u7801\u6709\u8bef,\u8bf7\u91cd\u65b0\u8f93\u5165!'); 
				$page_ipt.val("");
				return; 
			}
		} else { 
			alert('\u9519\u8bef\u7684\u6307\u4ee4\u64cd\u4f5c'); 
			return; 
		}
		var store = new LeopardStorage('dptlister.page');
		store.set(location.href + '#' + dptl.options.ID, new String(pagenum));
		$root.find('#dptl_page_num').val(pagenum); 
		dptl.list(true);
	}
};